package com.test.ref;

import sun.misc.Unsafe;

import java.lang.ref.WeakReference;

/**
 * Created by jl on 2018/10/29 0029
 */
public class WeakReferenceDemo {

    static class ContainsStrongRef {
        private String strong = new String("strong");
    }

    public static void main(String[] args) {
        WeakReference<String> a = new WeakReference<>(new String("123"));
        System.out.println(a.get());
        System.gc();
        System.out.println(a.get());

        // weak ref contains strong ref
        System.out.println("--------weak contains strong----------");
        WeakReference<ContainsStrongRef> weakStrong = new WeakReference<>(new ContainsStrongRef());
        String outerStrong = weakStrong.get().strong;
        System.out.println("weakStrong self：" + weakStrong.get());
        System.out.println("strong in weak：" + weakStrong.get().strong);
        System.gc();
        System.out.println("after gc .........");
        System.out.println(outerStrong);
        System.out.println("weakStrong self：" + weakStrong.get());
        System.out.println("strong in weak：" + weakStrong.get().strong);

        // thread local
        // thread local中真正存储这些键值对的Entry的key却是WeakReference的
        // 但key却是threadLocal本身，而这里我们又对threadLocal本身有着强引用，所以没被回收
        System.out.println("-------- for thread local ---------");
        ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        threadLocal.set(new Integer(520));
        System.gc();
        System.out.println(threadLocal.get());
        // 将强引用置为null,可将key给会收掉
        threadLocal = null;
        System.gc();
    }
}
